<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="任务编号" prop="taskCode">
          <el-input
            v-model="queryParams.taskCode"
            placeholder="请输入任务编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入任务名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工单编码" prop="workorderCode">
          <el-input
            v-model="queryParams.workorderCode"
            placeholder="请输入工单编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工单名称" prop="workorderName">
          <el-input
            v-model="queryParams.workorderName"
            placeholder="请输入工单名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input
            v-model="queryParams.processName"
            placeholder="请输入工序名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable size="small">
            <el-option
              v-for="dict in dict.type.mes_task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
      <el-table
        border
        v-loading="loading"
        :data="proTaskList"
        @current-change="handleCurrent"
      >
        <!--        <el-table-column width="55" align="center">
                  <template v-slot="scope">
                    <el-radio v-model="selectedTaskId" :label="scope.row.taskId" @change="handleRowChange(scope.row)">{{ "" }}
                    </el-radio>
                  </template>
                </el-table-column>-->
        <el-table-column type="index" label="序号" align="center"/>
        <el-table-column label="任务编号" width="120px" align="center" prop="taskCode">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)" v-hasPermi="['mes:pro:feedback:query']"
            >{{ scope.row.taskCode }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="任务名称"
          width="180px"
          align="center"
          prop="taskName"
          :show-overflow-tooltip="true"/>
        />
        <el-table-column
          label="工单编号"
          width="150px"
          align="center"
          prop="workorderCode"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="工单名称"
          width="120px"
          align="center"
          prop="workorderName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="工作站名称"
          width="150px"
          align="center"
          prop="workstationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="车间名称" align="center" prop="workshopName" :show-overflow-tooltip="true"/>
        <el-table-column
          label="工艺名称"
          align="center"
          prop="routeName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="工序名称" align="center" prop="processName" :show-overflow-tooltip="true"/>
        <el-table-column
          label="工序编号"
          align="center"
          prop="processCode"
          width="180"
          :show-overflow-tooltip="true"/>
        />
        <el-table-column label="任务颜色" align="center" prop="colorCode">
          <template slot-scope="scope">
            <el-color-picker v-model="scope.row.colorCode" disabled></el-color-picker>
          </template>
        </el-table-column>
        <el-table-column label="计划开工时间" align="center" prop="startTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划完工时间" align="center" prop="endTime " width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划生产时长" align="center" prop="duration" width="100" :show-overflow-tooltip="true"/>
        <el-table-column label="实际开工时间" align="center" prop="actualStartTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.actualStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际完工时间" align="center" prop="actualEndTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.actualEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际生产时长" align="center" prop="actualDuration" width="100" :show-overflow-tooltip="true"/>
        <el-table-column fixed="right" label="排产数量" align="center" prop="quantity" width="100">
          <template slot-scope="scope">
            <el-tag type="danger">{{ scope.row.quantity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="合格品数量" align="center" prop="quantityQuanlify" width="100">
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.quantityQuanlify }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.mes_task_status"
              :value="scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="280px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="handleCancel(scope.row)"
              v-hasPermi="['mes:pro:protask:start']"
              v-if="scope.row.status == 'PROGRESS'"
            >取消
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAddFeedback(scope.row)"
              v-hasPermi="['mes:pro:protask:end']"
              v-if="scope.row.status == 'PROGRESS'"
            >报工
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleStart(scope.row)"
              v-hasPermi="['mes:pro:protask:start']"
              v-if="scope.row.status == 'PENDUING'"
            >开工
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-position"
              @click="handleOutsource(scope.row)"
              v-hasPermi="['pro:outsourcingplan:add']"
              v-if="scope.row.status == 'PENDUING'"
            >外协
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-success"
              @click="handleFinished(scope.row)"
              v-hasPermi="['mes:pro:protask:end']"
              v-if="scope.row.status == 'PROGRESS'"
            >完工
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-remove"
              @click="handleDied(scope.row)"
              v-hasPermi="['mes:pro:protask:query']"
              v-if="scope.row.status !== 'DIED' && scope.row.status !== 'FINISHED'"
            >中止
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleReStart(scope.row)"
              v-hasPermi="['mes:pro:protask:start']"
              v-if="scope.row.status === 'FINISHED' && scope.row.doAgain === 'Y'"
            >开工
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              @click="handleReStart2(scope.row)"
              v-hasPermi="['mes:pro:protask:start']"
              v-if="scope.row.status === 'DIED'"
            >开启
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-printer"
              @click="handlePrint(scope.row)"
              v-hasPermi="['mes:pro:protask:start']"
              v-if="scope.row.status === 'PROGRESS'"
            >打印
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <TaskView v-if="infoOpen" ref="taskView" :optType="optType"></TaskView>
    <FeedBack v-if="feedBackOpen" ref="feedBack" @cancel="cancel"></FeedBack>
    <LabelTask v-if="printOpen" ref="labelTask" @cancel="cancel"></LabelTask>
    <el-dialog :title="outsourceTitle" :visible.sync="outsourceOpen" width="1080px" append-to-body>
      <el-form ref="outsourceForm" :model="outsourceForm" label-width="100px" :rules="outsourceRules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划编号" prop="planNo">
              <el-input v-model="outsourceForm.planNo" placeholder="请输入计划编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)"
              >
              </el-switch>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="需求日期" prop="deadline">
              <el-date-picker
                clearable
                v-model="outsourceForm.deadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <!--          <el-col :span="12">
                      <el-form-item label="生产商" prop="manufactureId" >
                        <el-select v-model="outsourceForm.manufactureId"  filterable  placeholder="请选择外协生产商" >
                          <el-option
                            v-for="out in outsourcedManufactureList"
                            :key="out.manufactureId"
                            :label="out.manufactureName"
                            :value="out.manufactureId"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>-->
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="outsourceForm.remarks" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelOutsource">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cancel, died, finish, getFirstCheck, listProtaskVo, restart, restart2, start } from "@/api/mes/pro/protask";
import UserSingleSelect from "@/components/userSelect/single.vue";
import TaskView from "@/views/mes/pro/task/taskView.vue";
import FeedBack from "@/views/mes/pro/task/feedBack.vue";
import LabelTask from "@/views/mes/pro/task/labelTask.vue";
import { genCode } from "@/api/system/autocode/rule";
import { transformToOutsource } from "@/api/mes/pro/outsourcingplan";


export default {
  name: "proTask",
  components: {
    FeedBack,
    TaskView,
    UserSingleSelect,
    LabelTask,
  },
  dicts: ["mes_task_status", "mes_feedback_type"],
  data() {
    return {
      printOpen: false,
      outsourcedManufactureList: [],
      autoGenFlag: false,
      feedBackOpen: false,
      optType: undefined,
      // 弹出层标题
      title: "",
      //外协弹窗
      outsourceTitle: "",
      // 是否显示弹出层
      open: false,
      outsourceOpen: false,
      shen: false,
      infoOpen: false,
      // 遮罩层
      loading: true,
      selectedTaskId: null,
      selectedRows: null,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产报工记录表格数据
      proTaskList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        taskName: null,
        workorderCode: null,
        workorderName: null,
        processName: null,
        status: null
      },
      // 表单参数
      form: {},
      outsourceForm: {
        planNo: null,
        taskCode: null,
        deadline: null,
        remarks: null
      },
      outsourceRules: {
        planNo: [
          {required: true, message: "计划编号不能为空", trigger: "blur"},
        ],
        deadline: [
          {required: true, message: "请选择需求日期", trigger: "blur"},
        ],

      },
      // 表单校验
      rules: {
        feedbackType: [
          {required: true, message: "报工类型不能为空", trigger: "change"},
        ],
        taskCode: [
          {required: true, message: "请选择生产任务", trigger: "blur"},
        ],
        workorderCode: [
          {required: true, message: "生产工单不能为空", trigger: "blur"},
        ],
        nickName: [
          {required: true, message: "请选择报工人", trigger: "blur"},
        ],
        feedbackTime: [
          {required: true, message: "请选择报工时间", trigger: "blur"},
        ],
      },

    };
  },
  created() {
    this.getList();
  },
  methods: {
    //自动生成编号
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('OUTSOURCE_PLAN_CODE').then(response => {
          this.outsourceForm.planNo = response;
        });
      } else {
        this.outsourceForm.planNo = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['outsourceForm'].validate(valid => {
        if (valid) {
          transformToOutsource(this.outsourceForm).then(response => {
            this.$modal.msgSuccess('新增成功');
            this.outsourceOpen = false;
            this.getList();
          });

        }
      });
    },
    /** 查询生产报工记录列表 */
    getList() {
      this.loading = true;
      this.selectedTaskId = undefined;
      listProtaskVo(this.queryParams).then((response) => {
        this.proTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCurrent(row) {
      if (row) {
        this.selectedTaskId = row.taskId;
        this.selectedRows = row;
      }
    },
    // 单选选中数据
    handleRowChange(row) {
      this.selectedRows = row;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.shen = false;
      this.getList();
    },
    cancelOutsource() {
      this.outsourceOpen = false;
      this.getList();
    },
    resetOutsource() {
      this.outsourceForm = {
        planNo: null,
        taskCode: null,
        deadline: null,

        remarks: null
      }
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        feedbackType: null,
        quantity: 0,
        quantityUncheck: 0,
        quantityFeedback: 0,
        quantityQualified: 0,
        quantityUnquanlified: 0,
        userName: null,
        nickName: null,
        feedbackChannel: null,
        feedbackTime: new Date(),
        recordUser: null,
        recordNick: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    // 查询明细按钮操作
    handleView(row) {
      const taskId = row.taskId;
      this.infoOpen = true;
      this.optType = 'view';
      this.$nextTick(() => {
        this.$refs.taskView.init(taskId);
      });
    },
    // 查询明细按钮操作
    handleFinished(row) {
      const taskId = row.taskId;
      this.infoOpen = true;
      this.optType = 'save';
      this.$nextTick(() => {
        this.$refs.taskView.init(taskId);
      });
    },
    //查看任务详情
    handleInfoView(row) {
      this.$router.push({path: '/taskInfo', query: {taskId: row.taskId}});
    },
    //外协
    handleOutsource(row) {
      this.resetOutsource()
      this.outsourceOpen = true;
      this.outsourceTitle = '添加外协计划信息';
      this.outsourceForm.taskCode = row.taskCode;

      /* listOutsourcedManufacture({pageSize: 1000,}).then(response => {
         this.outsourcedManufactureList=response.rows;

       });*/
    },

    //开工
    handleStart(row) {
      this.$modal
        .confirm('开工后任务将进入生产中状态，是否继续？')
        .then(function () {
          return start({taskId: row.taskId});
        })
        .then(() => {
          this.getList();
          getFirstCheck(row.taskId).then((res) => {
            if (res.data === 'Y') {
              this.$modal.msgError("该任务需要首件检验，请先进行首检操作！首检后才能正常报工！");
            }
          });
          this.$modal.msgSuccess("开工成功");
        })
        .catch(() => {
        });
    },
    //完工
    handleEnd(row) {
      this.$modal
        .confirm('任务完工后将不可报工，是否确认完工？')
        .then(function () {
          return finish({taskId: row.taskId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("完工成功");
        })
        .catch(() => {
        });
    },
    //报工
    handleAddFeedback(row) {
      this.reset();
      this.feedBackOpen = true;
      this.title = '生产报工';
      this.$nextTick(() => {
        this.$refs.feedBack.init(row.taskId);
      });
    },
    //取消开工
    handleCancel(row) {
      this.$modal
        .confirm('是否确认取消开工？')
        .then(function () {
          return cancel({taskId: row.taskId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {
        });
    },
    // 终止
    handleDied(row) {
      this.$modal
        .confirm('是否确认中止任务？')
        .then(function () {
          return died({taskId: row.taskId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {
        });
    },
    //开工
    handleReStart(row) {
      this.$modal
        .confirm('开工后任务将进入生产中状态，是否继续？')
        .then(function () {
          return restart({taskId: row.taskId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("开工成功");
        })
        .catch(() => {
        });
    },
    //开工
    handleReStart2(row) {
      this.$modal
        .confirm('是否确认开启任务？')
        .then(function () {
          return restart2({taskId: row.taskId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {
        });
    },
    handlePrint(row) {
      this.printOpen = true;
      this.title = '批次标签打印';
      this.$nextTick(() => {
        this.$refs.labelTask.init(row.taskId);
      });
    },
  },
};
</script>
